<?php
/**
 * 常用帮助类
 * @author caozhong
 * @version 2016-11-15
 */
namespace app\commands;

use Yii;
use yii\base\Exception;
use app\commands\Validator;


class Token{

    /**
     * 验证封装类
     *
     * @param array $data 验证数据
     * @param array $rules 验证规则
     * @return boolean|array 验证通过返回 false 不通过 抛出参数错误异常array('code'=>105,'message'=>'参数错误描述')
     */
    public static function validator($data, $rules, $messages = array(),$ajax=1)
    {
        $validator = Validate::make($data, $rules,$messages);

        if ($validator->fails()) {
            foreach ($validator->messages()->all() as $message) {
                //$return = $this->failed($message);
                return  ['err'=>1,'msg'=>$message,'code'=>400];
            }
        }
        return true;
    }




    /**
     * @param $array
     * @param int $num
     * @param bool $jsonHeader
     * 输出标准json
     * @return   string
     */
    public static function output_json($array, $num = true, $jsonHeader = true) {
        header("Expires: Mon, 26 Jul 1970 01:00:00 GMT");
        $jsonHeader && header('Content-type: application/json;charset=utf-8');
        header("Pramga: no-cache");
        header("Cache-Control: no-cache");
        if ($num) {
            //callback 方式
            if(isset($array['callback']) && !empty($array['callback'])){
                $callback = $array['callback'];
                $result = json_encode((array)($array), JSON_NUMERIC_CHECK);
                exit( $callback."(". $result .")" );
            }
            exit(json_encode((array)($array), JSON_NUMERIC_CHECK));
        } else {
            if(isset($array['callback']) && !empty($array['callback'])){
                $callback = $array['callback'];
                $result = json_encode((array)($array));
                exit( $callback."(". $result .")" );
            }
            exit(json_encode((array)($array)));
        }
    }

    /**
     * @desc 获取时间 毫秒级
     * @author chris.gong
     */
    public static function microtime_float(){
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }

    /**
     * @desc 接口错误异常输出预组装数据
     * @param array arr 返回的数组
     * @param code  错误码
     * @param  msg 错误信息
     */
    public static function err_out($arr, $code, $msg, $f=false){
        $arr['response_time'] = self::microtime_float() . '';
        $arr['error']['code'] = $code;
        $arr['error']['message'] = $msg;
        self::log_file($arr,true);
        self::output_json($arr, $f);
    }

    /**
     * @desc 接口正常返回数据信息 预处理
     * @param arr  客户端携带的参数值数组 $_GET
     * @param arr2  业务逻辑数据数组
     */
    public static function right_out($arr,$arr2,$f=false){
        $arr['result'] = $arr2;
        $arr['response_time'] = self::microtime_float() . '';
        self::output_json($arr,$f);
    }

    /**
     * 校验手机号
     */
    public static function checkPhone($phone){
        if(!$phone){
            return true;
        }
        if(preg_match('/^1[34578]{1}\d{9}$/', $phone)){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 日志log
     */
    public static function log_file($str,$force=false){
        if(!$force){
            return true;
        }
        $t = date("Y-m-d H:i:s");
        if (is_array($str)) {
            $str = "--- print array ---\n".var_export($str, true);
        }
        $_log_dir = Yii::$app->basePath . "/runtime/logs/" . date("Y") . "/" . date("m") . '/';
        if(!file_exists($_log_dir)){
            mkdir($_log_dir, 0777, TRUE);
        }
        $_log_file = $_log_dir . date("d") . ".log";
        $str = '['.date("m-d H:i:s").'] '.$t.' '.$str."\n";
        error_log($str, 3, $_log_file);
    }


    /**
     * 进行验签  验签通过  返回当前的用户信息
     * @param  true  true 返回true | false ， false ： 返回用户信息
     *
     */
    public static function checksign($arr,$true=false){
        $token = $arr['token'];
        if(empty($token)){
            self::right_out($arr,array('code'=>'-1','msg'=>'smgid参数必需'));
        }

        $r_userinfo=UserInfo::get_userinfo($token);
        if(!empty((array)$r_userinfo)){
            return $r_userinfo;
        }else{
            self::right_out($arr,array('code'=>'-1','msg'=>'您无权限操作'));
        }
    }

    /**
     * 数字万处理
     */
    public static function num_wan($num){
        $num = intval(str_replace(',','',$num));
        if($num > 9999){
            $count = round($num / 10000, 1) . '万';
        }else{
            $count = intval($num).'';
        }
        return $count;
    }

    /**
     *  功能：用来过滤数字，字符串和字符串数组，防止被挂马和sql注入
     *  参数$data，待过滤的数字.字符串或字符串数组，
     *   $force为true，忽略get_magic_quotes_gpc
     */
    public static function in($data, $force = false){
        if(is_string($data)){
            $data = trim($data);//防止被挂马，跨站攻击
            $data = addslashes($data);//防止sql注入
            $data = str_replace('%', '\%', $data);    // 把 '%'过滤掉
            $data = nl2br($data);    // 回车转换  ;
            $data = htmlspecialchars($data, ENT_QUOTES);
            return $data;
        } else if(is_array($data)) {
            foreach($data as $key => $value){
                $data[$key] = self::in($value, $force);
            }
            return $data;
        } else {
            return $data;
        }
    }

    //反转义
    public static function solve($str){
        if($str){
            //过滤js
            $str = preg_replace('/script/i', '',  $str);
            return stripslashes(htmlspecialchars_decode($str, ENT_QUOTES));
        }
        return $str;
    }


    /**
     * @param $uri
     * @param bool $data
     * @return bool|mixed
     */
    public static function ihub_curl($uri, $data=FALSE, $times=5,$logs = true, $type='post'){
        $ch = curl_init();
        if($type == 'post'){
            curl_setopt($ch, CURLOPT_POST, 1);
        }
        curl_setopt($ch, CURLOPT_URL, $uri);
        if(false != $data && !empty($data)){
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data,JSON_UNESCAPED_UNICODE));
        }

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $times);
        $r = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($r ,true);

        if($logs){
            self::log_file($uri,TRUE);
            self::log_file(json_encode($data),TRUE);
            self::log_file($result,TRUE);
        }

        if($result){
            return $result;
        }else{
            return false;
        }
    }

    /**
     * 处理 加工用户信息
     */
    public static function handel_userinfo($userinfo){
        $res = $orim = $return = $peimiss = [];
        if(!empty($userinfo) && count($userinfo['data']['peimission'])){
            $data = $userinfo['data'];
            foreach($data['peimission'] as $key => $val){
                if($val['product_id'] == 4){
                    $res[$val['flow_type']] = $val;
                    $orim[$val['organization_id']] = array(
                        'organization_id'=>$val['organization_id'],
                        'organization_name'=>$val['organization_name']
                    );
                }
            }
            $return['id'] = $data['id'];
            $return['username'] = $data['username'];
            $return['truename'] = $data['truename'];
            $return['avatar'] = $data['avatar'];
            $return['sex'] = $data['sex'];
        }
        ksort($res);
        if(!empty($res)){
            $h = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $host = $h . $_SERVER['HTTP_HOST'];
            foreach ($res as $k=>$v){
                $vals = [];
                $vals['title'] = $v['title'];
                $vals['role'] = $k;
                $vals['url'] = $host.Yii::$app->params['Role_front_url'][$k];
                $peimiss[] = $vals;
            }
        }
        $return['peimiss'] = $peimiss;
        $return['orim'] = $orim;
        return $return;
    }

    /*
     * 过滤用户昵称里面的特殊字符
     * @param string    $str   待输出的用户昵称
     */
    public static function jsonName($str) {
        if($str){
            $tmpStr = json_encode($str);
            $tmpStr2 = preg_replace("#(\\\ud[0-9a-f]{3})#i","",$tmpStr);
            $return = json_decode($tmpStr2);
            if(!$return){
                return self::jsonName($return);
            }
        }else{
            $return = '微信用户-'.time();
        }
        return $return;
    }


    /*参数1：访问的URL，
    参数2：post数据(不填则为GET)，
    参数3：提交的$cookies,参数4：
    是否返回$cookies*/
    public static function weibo_curl($url, $post='', $cookie='', $returnCookie=0){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
        }
        if($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        if($returnCookie){
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
            $info['cookie']  = substr($matches[1][0], 1);
            $info['content'] = $body;
            return $info;
        }else{
            return $data;
        }
    }

    /**
     * 为导出格式化数据
     * 将二维数组 处理成tr  td格式
     */
    public static function arrTotrtd($arr){
        $str ='';
        if(!empty($arr)){
            foreach ($arr as $key=>$val){
                $str .= '<tr>';
                if(!empty($val)){
                    foreach ($val as $k=>$v){
                        $str .= '<td>'. iconv('utf-8', 'gbk', $v) .'</td>';
                    }
                }
                $str .= '</tr>';
            }
        }
        return $str;
    }

    /**
     * @desc  导出excel  2007版本
     * @param  filename  导出文件名  中奖名单.xls
     * @param  table  数据内容， tr td 汉字经过转义 iconv('utf-8', 'gbk', '序号')
     */
    public static function exportExcelNew($table){
        // header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        // header("Content-Disposition:attachment;filename=".$filename);
        return "<table border=1>".$table."</table>";
    }

    public static function exportWord($table){
        // header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        // header("Content-Disposition:attachment;filename=".$filename);
        return "<table border=1>".$table."</table>";
        // header('pragma:public');
        // header('Content-type:application/vnd.ms-word;charset=utf-8;name="'.$xlsTitle.'.doc"');
        // header("Content-Disposition:attachment;filename=$fileName.doc");//attachment新窗口打印inline本窗口打印
        // header( 'Content-Type: image/jpeg');

    }


    /**
     * 输出信息
     */
    public static function dd(){
        print_r(func_get_args());
        die;
    }

}